package com.oop.example.gui;

import com.oop.example.data.EntryPOJO;
import com.oop.example.data.HibernateUtil;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.classic.Session;

public class ExportHeaders extends javax.swing.JDialog {

    public ExportHeaders(Window parent) {
        super(parent, ModalityType.APPLICATION_MODAL);
        initComponents();
        jButton1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                new Thread(new ParsingTask(new File(jTextFieldPath.getText()))).start();
            }
        });
    }

    private class ParsingTask implements Runnable {

        private File exportFile = null;
        private List<String> headers = new ArrayList<String>();

        public ParsingTask(File exportFile) {
            this.exportFile = exportFile;
        }

        @Override
        public void run() {
            int counter = 0;
            //Извлечение массива данных из БД
            indicator.setText("Извлечение массива данных из БД");
            ArrayList<EntryPOJO> items = new ArrayList<EntryPOJO>();
            try {
                Session openSession = HibernateUtil.getSessionFactory().openSession();
                Query createQuery = openSession.createQuery("select a from EntryPOJO a order by a.ID");
                System.out.println(createQuery.getQueryString());
                List list = createQuery.list();
                for (Object o : list) {
                    counter++;
                    indicator.setText(">> " + counter);
                    if (o instanceof EntryPOJO) {
                        EntryPOJO pojo = (EntryPOJO) o;
                        items.add(pojo);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
            int count = 0;
            //Формирование массива Entry
            indicator.setText("Парсинг");
            counter = 0;
            for (EntryPOJO pojo : items) {
                counter++;
                indicator.setText("parsing>> " + headers.size());
                try {
                    //EntryHandler handler = new EntryHandler();
                    //handler.setEntryPOJO(pojo);
                    //handler.veryLiteHandle();
                    //headers.add(handler.getHeader());
                } catch (Exception ex) {
                    System.out.println("ex " + ex.getMessage());
                    count++;
                }
            }
            indicator.setText("Сортировка");
            Collections.sort(headers);


            //Сохранение в файл
            indicator.setText("Сохранение в файл");
            try {
                StringBuffer sb = new StringBuffer();
                for (String s : headers) {
                    sb.append(s).append("\n");
                }
                write(exportFile, sb);
            } catch (Exception ex) {
                ex.printStackTrace(System.out);
            }
            indicator.setText("Готово!");
        }
    }

    public static void write(File f, StringBuffer sb) {
        try {
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
            out.write(sb.toString());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        indicator = new javax.swing.JTextPane();
        jLabelFile = new javax.swing.JLabel();
        jTextFieldPath = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton1.setText("Выгрузить");

        jScrollPane1.setViewportView(indicator);

        jLabelFile.setText("File");

        jTextFieldPath.setText("headers.txt");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldPath, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelFile)
                    .addComponent(jTextFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane indicator;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabelFile;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldPath;
    // End of variables declaration//GEN-END:variables
}
